<?php
include_once 'modules/Pay.php';

// 文章管理
class PostAction extends BaseAction {

  public function genWord($fileName) {
    $filePath = $this->basePath.'Uploads/file/'.$fileName;
    $outputFilePath = $this->basePath.'Uploads/file/'.$fileName.'.html';
    $mediaFolderName = Tools::getSalt();
    $mediaFolder = $this->basePath.'Uploads/fileMedia/'.$mediaFolderName;
    $mediaFolderPath = $mediaFolder.'/';
    if(!file_exists($mediaFolderPath)) {
      mkdir($mediaFolderPath, 0777, true);
    }
    $command = "pandoc --extract-media $mediaFolder -s $filePath -o $outputFilePath 2>&1";
    $result = shell_exec($command);
    // print_r(iconv('GB2312', 'UTF-8', $result));
    
    if(file_exists($outputFilePath)) {
      $content = file_get_contents($outputFilePath);
      $replacedContent = str_replace($this->basePath, '/track/', $content);
      $replacedContent = str_replace('<meta charset="utf-8" />', '<meta charset="utf-8" /><link rel="stylesheet" href="//res.wx.qq.com/open/libs/weui/1.1.3/weui.min.css"/>', $replacedContent);
      file_put_contents($outputFilePath, $replacedContent);
    }else {
      return false;
    }
  }

  public function genExcel($fileName) {
    $filePath = $this->basePath.'Uploads/file/'.$fileName;
    $outputFilePath = $this->basePath.'Uploads/file/'.$fileName.'.html';

    $table = '<table>';
    $theadRowHtml = '';
    $tbodyRows = array();

    $objPHPExcel = PHPExcel_IOFactory::load($filePath);
    $objWorksheet = $objPHPExcel->getActiveSheet();
    $highestRow = $objWorksheet->getHighestRow();
    $highestColumn = $objWorksheet->getHighestColumn();
    $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
    for ($row = 1; $row <= $highestRow; ++$row) {
      $cellList = array();
      for ($col = 0; $col < $highestColumnIndex; ++$col) {
        $val = $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
        $cellTag = $row === 1 ? 'th' : 'td';
        $cellList[] = "<$cellTag>$val</$cellTag>";
      }
      $rowHtml = "<tr>".implode('', $cellList)."</tr>";
      if($row === 1) {
        $theadRowHtml = "<thead>$rowHtml</thead>";
      }else {
        $tbodyRows[] = $rowHtml;
      }
    }
    $tbodyRowHtml = "<tbody>".implode('', $tbodyRows)."</tbody>";

    $table = '<table>'.$theadRowHtml.$tbodyRowHtml.'</table>';
    $html = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><link rel="stylesheet" href="//res.wx.qq.com/open/libs/weui/1.1.3/weui.min.css"/><style>table{border-spacing: 0;border-collapse:collapse;}table th, table td{border: 1px solid #e8e8e8;white-space:nowrap;padding: 4px 8px;}</style></head><body><div style="overflow: auto;">'.$table.'</div></body></html>';
    
    file_put_contents($outputFilePath, $html);
  }

  private function genVideoPost($fileName) {
    $filePath = $this->basePath.'Uploads/video/'.$fileName;
    $outputFilePath = $this->basePath.'Uploads/poster/'.$fileName.'.jpg';

    $command = "ffmpeg -i ".$filePath." -y -f mjpeg -ss 3 -t 1 ".$outputFilePath." 2>&1";
    $result = shell_exec($command);
    // print_r(iconv('GB2312', 'UTF-8', $result));
  }

  /**
   * 添加文章
   * @return ajaxObject
   */
  public function create() {
    $typeMap = array('1' => 'video' , '2' => 'file', '3' => 'photo');

    // 缩略图
    if($this->request['post_thumb_url']) {
      parent::moveUploadFromTemp('thumb', $this->request['post_thumb_url']);
    }

    // 附件处理
    $fileName = $this->request['post_file_url'];
    if($fileName) {
      $type = $typeMap[$this->request['post_type']];
      parent::moveUploadFromTemp($type, $fileName);
      if ($this->request['post_type'] == 2) {
        $isWord = strpos($fileName, '.docx');
        if($isWord !== false) {
          $this->genWord($fileName);
        } else {
          $this->genExcel($fileName);
        }
      } else if ($this->request['post_type'] == 1) {
        // 生成缩略图
        $this->genVideoPost($fileName);
      }
    }

    // 红包文章默认状态为-1，即待支付状态
    if($this->request['post_type'] === '0') $this->request['post_status'] = -1;

    $ret = parent::_modelDoAdd('Post');
    if(intval($ret) > 0) {
      // 红包文章
      if($this->request['post_type'] === '0') {
        // 生成红包记录
        $redpacketResult = $this->genRedPacketList($ret);

        // 生成支付订单
        $userId = $_SESSION['trackUser']['admin_id'];
        $orderData = Pay::order('wechat', $this->request['platform'], $ret, $userId, $this->request['openId']);
      }

      $this->ajaxReturn($orderData, '添加文章成功', 1);
    }else {
      $this->ajaxReturn(trace(), $ret, 0);
    }
  }

  /**
   * 生成红包
   * @param int $postId 帖子id
   * @return void
   */
  private function genRedPacketList($postId) {
    $postData = M("Post")->find($postId);
    $num = intval($postData['post_redpacket_num']);
    $rule = $postData['post_redpacket_rule'];
    $total = intval($postData['post_redpacket_price']);

    $list = [];
    if($rule === '0') {
      // 等额分配红包
      $avg = floor($total / $num * 100) / 100;
      for ($i=0; $i < $num; $i++) { 
        $addData['rp_postid'] = $postId;
        $addData['rp_price'] = $avg;
        $list[] = $addData;
      }
    } else {
      // 随机红包
      // 因微信红包接口的额度范围为1-200，因此先从总金额中给每个人分1元，再添加随机量
      $remain = $total - $num;
      if($remain < 0) return false;
      for ($i=0; $i < $num; $i++) { 
        $addData['rp_postid'] = $postId;
        if($i === $num - 1) {
          $addData['rp_price'] = 1 + $remain;
        } else {
          $remainSize = $num - $i;
          $max = $remain / $remainSize * 2;
          if($max * 100 > 1) {
            $curPrice = rand(1, $max * 100) / 100;
          }else {
            $curPrice = 0;
          }
          $addData['rp_price'] = 1 + $curPrice;
          $remain -= $curPrice;
        }
        $list[] = $addData;
      }
    }

    return M("RedpacketList")->addAll($list);
  }

  /**
   * 文章列表
   * @return ajaxObject
   */
  public function postList() {
    $conditions['post_createdby'] = $_SESSION['trackUser']['admin_id'];
    $conditions['post_type'] = $this->request['post_type'];
    $currentPage = $this->request['p'] ? $this->request['p'] : 1;

    $data = parent::_modelList('PostView', 'post_updated desc', array(), $conditions);

    $postList = $data['list'] ? $data['list'] : array();

    // 最近活动时间：5分钟前
    $timeNow = time();
    $lastActiveTime = $timeNow - 5 * 60;
    $Log = M("Log");

    $Model = new Model();
    
    foreach ($postList as $key => $value) {
      $con['log_post_id'] = $value['post_id'];
      $sql ="SELECT COUNT(*) c FROM (SELECT DISTINCT log_user_openid FROM track_log WHERE log_post_id = ".$value['post_id'].") t";
      $countRes = $Model->query($sql);

      $postList[$key]['post_track_num'] = $countRes[0]['c'];
      $con['log_created'] = array('gt', $lastActiveTime);
      $postList[$key]['post_last_tracked'] = $Log->where($con)->order('log_created desc')->getField('log_created');
    }

    $ret['list'] = $postList;
    $ret['pagination']['total'] = intval($data['count']);
    $ret['pagination']['pageSize'] = 10;
    $ret['pagination']['current'] = $currentPage;

    $this->ajaxReturn($ret, trace(), 1);
  }

  /**
   * 文章详情
   * @return ajaxObject
   */
  public function postDetail() {
    $id = $this->request['id'];
    $ret = parent::_modelDetail('PostView', 'post_id', $id);

    $con['log_post_id'] = $id;
    $ret['post_track_num'] = M('Log')->where($con)->count();

    // 获取用户维度的最近关怀信息
    $Model = new Model();
    $limit = parent::_getPageLimit();
    $countSql = "SELECT COUNT(*) c FROM track_log ta, (SELECT MAX(log_id) max_id, log_user_openid FROM track_log GROUP BY log_user_openid) tb WHERE ta.log_id = tb.max_id";
    $countResult = $Model->query($countSql);

    $sql = "SELECT ta.* FROM track_log ta, (SELECT MAX(log_id) max_id, log_user_openid FROM track_log WHERE log_post_id = $id GROUP BY log_user_openid) tb WHERE ta.log_id = tb.max_id ORDER BY log_created desc LIMIT $limit";
    $trackResult = $Model->query($sql);
    if(!$trackResult) $trackResult = array();

    $ret['track']['list'] = $trackResult;
    $ret['track']['pagination']['total'] = intval($countResult[0]['c']);
    $ret['track']['pagination']['pageSize'] = 10;
    $ret['track']['pagination']['current'] = $this->request['p'] ? $this->request['p'] : 1;

    $this->ajaxReturn($ret, trace(), 1);
  }

  /**
   * 上传缩略图
   * @return ajaxObject
   */
  public function uploadThumb() {
    $config['allowExts'] = array('jpg', 'jpeg', 'png', 'gif', 'bmp');
    $config['thumb']['width'] = 150;
    $config['thumb']['height'] = 150;
    $result = parent::upload($config);
    $this->ajaxReturn($result);
  }

  /**
   * 上传图片
   * @return ajaxObject
   */
  public function uploadPhoto() {
    $config['allowExts'] = array('jpg', 'jpeg', 'png', 'gif', 'bmp');
    $config['thumb']['width'] = 750;
    $config['thumb']['height'] = 1600;
    $result = parent::upload($config);
    $this->ajaxReturn($result);
  }

  /**
   * 上传视频
   * @return ajaxObject
   */
  public function uploadVideo() {
    $config['allowExts'] = array('mp4', 'ogg', 'webm', 'mov');
    $result = parent::upload($config);
    $this->ajaxReturn($result);
  }

  /**
   * 上传文件
   * @return ajaxObject
   */
  public function uploadFile() {
    $config['allowExts'] = array('xls', 'xlsx', 'csv', 'docx');
    $result = parent::upload($config);
    $this->ajaxReturn($result);
  }

  public function wechat() {
    $tools = new JsApiPay();
    $openId = $tools->GetOpenid();

    $url = 'https://'.$_SERVER['HTTP_HOST'].'/track/web/dist/index.html#/dashboard/redpacket?openid='.$openId;
    Header("Location: $url");
  }
}